package com.circle.rest.core.exception;

import com.circle.rest.core.common.model.ErrorResponseData;
import com.circle.rest.core.util.ToolUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: RestfulApi
 * @description: 全局异常拦截器
 * @author: 赵航
 * @create: 2019-03-07 09:26
 **/
@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Object handleException(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            return new ErrorResponseData(404, e.getMessage());
        }
        return new ErrorResponseData(e.getMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public Object serviceException(HttpServletRequest request, ServiceException e) {
        Integer code = e.getCode();
        String message = e.getMessage();

        if (ToolUtil.isEmpty(code)) {
            code = ExceptionEnum.SERVICE_ERROR.code();
        }
        if (ToolUtil.isEmpty(message)) {
            message = ExceptionEnum.SERVICE_ERROR.msg();
        }

        return new ErrorResponseData(code, message);
    }
}
